<template>
  <div class="order-detail">
    <!-- 头部 -->
    <header>
      <i class="fa fa-arrow-left" @click="goBack"></i>
      <div class="title">订单详情</div>
      <div class="placeholder"></div>
    </header>

    <div class="content" v-if="orderInfo">
      <!-- 订单状态卡片 -->
      <div class="status-card">
        <div class="status-icon">
          <i :class="getStatusIcon(orderInfo.orderState)"></i>
        </div>
        <div class="status-info">
          <div class="status-text">{{ getStatusText(orderInfo.orderState) }}</div>
          <div class="status-desc">{{ getStatusDesc(orderInfo.orderState) }}</div>
        </div>
      </div>

      <!-- 商家信息 -->
      <div class="info-card">
        <div class="card-title">
          <i class="fa fa-shopping-bag"></i>
          <span>商家信息</span>
        </div>
        <div class="business-info">
          <div class="business-logo" v-if="orderInfo.businessImg">
            <img :src="orderInfo.businessImg" alt="商家Logo">
          </div>
          <div class="business-detail">
            <div class="business-name">{{ orderInfo.shopName || orderInfo.businessName || '未知商家' }}</div>
            <div class="business-contact" v-if="orderInfo.businessPhone">
              <i class="fa fa-phone"></i>
              <span>{{ orderInfo.businessPhone }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 配送信息 -->
      <div class="info-card">
        <div class="card-title">
          <i class="fa fa-map-marker"></i>
          <span>配送信息</span>
        </div>
        <div class="delivery-info" v-if="deliveryAddress">
          <div class="address-info">
            <div class="contact-row">
              <div class="contact">
                <span class="name">{{ deliveryAddress.contactName }}</span>
                <span class="phone">{{ deliveryAddress.contactTel }}</span>
              </div>
              <div class="tag">收货地址</div>
            </div>
            <div class="address">
              <i class="fa fa-map-marker"></i>
              <span>{{ deliveryAddress.address }}</span>
            </div>
          </div>
        </div>
        <div class="no-address" v-else>
          <i class="fa fa-map-marker"></i>
          <span>暂无配送信息</span>
        </div>
      </div>

      <!-- 订单信息 -->
      <div class="info-card">
        <div class="card-title">
          <i class="fa fa-file-text-o"></i>
          <span>订单信息</span>
        </div>
        <div class="order-info-list">
          <div class="info-item">
            <span class="item-label">订单编号</span>
            <span class="item-value">{{ orderInfo.orderId }}</span>
          </div>
          <div class="info-item">
            <span class="item-label">下单时间</span>
            <span class="item-value">{{ getOrderTime() }}</span>
          </div>
          <div class="info-item" v-if="getPayTime()">
            <span class="item-label">支付时间</span>
            <span class="item-value">{{ getPayTime() }}</span>
          </div>
        </div>
      </div>

      <!-- 商品列表 -->
      <div class="info-card">
        <div class="card-title">
          <i class="fa fa-list"></i>
          <span>商品列表</span>
        </div>
        <div class="food-list">
          <div v-if="!getOrderItems().length" class="empty-data">
            暂无商品数据
          </div>
          <div class="food-item" v-for="(item, index) in getOrderItems()" :key="index">
            <div class="food-info">
              <div class="food-detail">
                <div class="food-name-row">
                  <span class="food-name">{{ item.foodName }}</span>
                  <span class="food-quantity">x{{ item.quantity }}</span>
                </div>
              </div>
            </div>
            <div class="food-price">¥{{ (item.foodPrice * item.quantity).toFixed(2) }}</div>
          </div>
        </div>
      </div>

      <!-- 费用明细 -->
      <div class="info-card">
        <div class="card-title">
          <i class="fa fa-credit-card"></i>
          <span>费用明细</span>
        </div>
        <div class="price-detail">
          <div class="price-item">
            <span class="item-label">商品金额</span>
            <span class="item-value">¥{{ getItemsTotal() }}</span>
          </div>
          <div class="price-item">
            <span class="item-label">配送费</span>
            <span class="item-value">¥{{ getDeliveryFee() }}</span>
          </div>
          <div class="price-item total">
            <span class="item-label">实付金额</span>
            <span class="item-value">¥{{ getOrderTotal() }}</span>
          </div>
        </div>
      </div>

      <!-- 底部操作按钮 -->
      <div class="action-bar" v-if="orderInfo.orderState === 0 || orderInfo.orderState === 'PENDING'">
        <button class="btn-cancel" @click="cancelOrder">取消订单</button>
        <button class="btn-pay" @click="payOrder">去支付</button>
      </div>
      <div class="action-bar" v-else-if="orderInfo.orderState === 2 || orderInfo.orderState === 'COMPLETED'">
        <button class="btn-again" @click="buyAgain">再来一单</button>
      </div>
    </div>

    <!-- 加载中 -->
    <div class="loading" v-else>
      <div class="loading-spinner">
        <i class="fa fa-spinner fa-spin"></i>
      </div>
      <div class="loading-text">加载中...</div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getOrderById } from '@/api/orders';
import { listOrderDetailByOrderId } from '@/api/orderDetail';
import { getFoodById } from '@/api/food';
import { getAddressById } from '@/api/address';
import { ElMessage, ElMessageBox } from 'element-plus';

const route = useRoute();
const router = useRouter();
const orderId = route.query.orderId;
const orderInfo = ref(null);
const orderDetails = ref([]);
const foodDetails = ref([]);
const deliveryAddress = ref(null);

// 获取订单信息
const fetchOrderInfo = async () => {
  try {
    const res = await getOrderById(orderId);
    if (res.code === 0) {
      orderInfo.value = res.data;
      
      // 获取配送地址信息
      if (orderInfo.value.daId) {
        const addressRes = await getAddressById(orderInfo.value.daId);
        if (addressRes.code === 0) {
          deliveryAddress.value = addressRes.data;
        }
      }
      
      // 获取订单详情
      await fetchOrderDetail();
    } else {
      ElMessage.error('获取订单信息失败');
    }
  } catch (error) {
    console.error('获取订单信息出错:', error);
    ElMessage.error('获取订单信息出错');
  }
};

// 获取订单详情（商品列表）
const fetchOrderDetail = async () => {
  try {
    const res = await listOrderDetailByOrderId(orderId);
    if (res.code === 0 && res.data) {
      orderDetails.value = res.data;
      
      // 获取每个食品的详细信息
      for (const item of orderDetails.value) {
        if (item.foodId) {
          await fetchFoodDetail(item.foodId);
        }
      }
    }
  } catch (error) {
    ElMessage.error('获取订单详情失败');
  }
};

// 获取食品详情
const fetchFoodDetail = async (foodId) => {
  try {
    const res = await getFoodById(foodId);
    if (res.code === 0 && res.data) {
      foodDetails.value.push(res.data);
    }
  } catch (error) {
    console.error('获取食品详情失败:', foodId);
  }
};

// 获取合并后的订单项目
const getOrderItems = () => {
  // 如果已有完整的orderItems数据，直接返回
  if (orderInfo.value && orderInfo.value.orderItems && orderInfo.value.orderItems.length > 0) {
    return orderInfo.value.orderItems;
  }
  
  // 合并订单详情和食品详情
  if (orderDetails.value && orderDetails.value.length > 0) {
    return orderDetails.value.map(item => {
      const foodDetail = foodDetails.value.find(food => food.foodId == item.foodId) || {};
      return {
        ...item,
        foodName: foodDetail.foodName || `商品(ID:${item.foodId})`,
        foodPrice: foodDetail.foodPrice || 0,
        foodImg: foodDetail.foodImg || ''
      };
    });
  }
  
  return [];
};

// 获取下单时间
const getOrderTime = () => {
  if (!orderInfo.value) return '暂无';
  return formatDate(new Date()); // 使用当前时间，可以根据实际情况修改
};

// 获取支付时间
const getPayTime = () => {
  return ''; // 这里可以根据实际情况修改
};

// 获取商品总价
const getItemsTotal = () => {
  const items = getOrderItems();
  if (!items || items.length === 0) {
    return '0.00';
  }
  
  const total = items.reduce((sum, item) => {
    return sum + (item.foodPrice * item.quantity);
  }, 0);
  
  return total.toFixed(2);
};

// 获取配送费
const getDeliveryFee = () => {
  if (!orderInfo.value) return '0.00';
  return '5.00'; // 这里可以根据实际情况修改
};

// 获取订单总价
const getOrderTotal = () => {
  const itemsTotal = parseFloat(getItemsTotal());
  const deliveryFee = parseFloat(getDeliveryFee());
  return (itemsTotal + deliveryFee).toFixed(2);
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '暂无';
  
  try {
    const date = new Date(dateString);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
  } catch (e) {
    return String(dateString);
  }
};

// 获取订单状态文本
const getStatusText = (status) => {
  // 将数值转换为数字类型，确保匹配
  const statusCode = typeof status === 'string' ? parseInt(status, 10) : status;
  
  const statusMap = {
    0: '待支付',
    1: '配送中',
    2: '已完成',
    3: '已取消',
    // 兼容字符串类型的状态码
    'PENDING': '待支付',
    'DELIVERING': '配送中',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  };
  
  return statusMap[statusCode] || '未知状态';
};

// 获取订单状态描述
const getStatusDesc = (status) => {
  // 将数值转换为数字类型，确保匹配
  const statusCode = typeof status === 'string' ? parseInt(status, 10) : status;
  
  const descMap = {
    0: '请尽快完成支付',
    1: '商家正在准备您的美食，骑手正在火速配送中',
    2: '订单已完成，欢迎再次光临',
    3: '订单已取消',
    // 兼容字符串类型的状态码
    'PENDING': '请尽快完成支付',
    'DELIVERING': '商家正在准备您的美食，骑手正在火速配送中',
    'COMPLETED': '订单已完成，欢迎再次光临',
    'CANCELLED': '订单已取消'
  };
  
  return descMap[statusCode] || '';
};

// 获取订单状态图标
const getStatusIcon = (status) => {
  // 将数值转换为数字类型，确保匹配
  const statusCode = typeof status === 'string' ? parseInt(status, 10) : status;
  
  const iconMap = {
    0: 'fa fa-clock-o',
    1: 'fa fa-motorcycle',
    2: 'fa fa-check-circle',
    3: 'fa fa-times-circle',
    // 兼容字符串类型的状态码
    'PENDING': 'fa fa-clock-o',
    'DELIVERING': 'fa fa-motorcycle',
    'COMPLETED': 'fa fa-check-circle',
    'CANCELLED': 'fa fa-times-circle'
  };
  
  return iconMap[statusCode] || 'fa fa-question-circle';
};

// 获取支付方式文本
const getPayMethod = (method) => {
  const methodMap = {
    'alipay': '支付宝',
    'wechat': '微信支付',
    'ALIPAY': '支付宝',
    'WECHAT': '微信支付'
  };
  
  return methodMap[method] || '在线支付';
};

// 返回按钮处理
const goBack = () => {
  // 获取来源标记
  const fromPage = route.query.from;
  
  // 根据不同的来源选择返回的目标页面
  if (fromPage === 'payment_result') {
    // 从支付结果页面进入的，返回首页
    router.push('/');
  } else if (fromPage === 'order') {
    // 从订单列表进入的，返回订单列表
    router.push('/order');
  } else {
    // 根据订单中的商家ID判断返回位置
    const businessId = orderInfo.value?.businessId;
    if (businessId) {
      router.push({
        path: '/businessInfo',
        query: { 
          businessId: businessId,
          foodTypeId: 1,
          from: 'index'
        }
      });
    } else {
      // 默认返回订单列表
      router.push('/order');
    }
  }
};

// 取消订单
const cancelOrder = async () => {
  try {
    await ElMessageBox.confirm('确定要取消该订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    // 这里需要添加取消订单的API调用
    // const res = await cancelOrderById(orderId);
    
    ElMessage.success('订单已取消');
    fetchOrderInfo(); // 刷新订单信息
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消订单失败');
    }
  }
};

// 去支付
const payOrder = () => {
  router.push({
    path: '/payment',
    query: { orderId: orderId }
  });
};

// 再来一单
const buyAgain = () => {
  const businessId = orderInfo.value?.businessId || 
                    orderInfo.value?.shopId || 
                    orderInfo.value?.merchantId;
  
  if (businessId) {
    router.push({
      path: '/businessInfo',
      query: { 
        businessId: businessId,
        foodTypeId: 1
      }
    });
  } else {
    ElMessage.warning('无法获取商家信息');
  }
};

onMounted(() => {
  if (!orderId) {
    ElMessage.error('订单ID不能为空');
    router.push('/orders');
    return;
  }
  
  fetchOrderInfo();
});
</script>

<style scoped lang="scss">
.order-detail {
  min-height: 100vh;
  background-color: #f7f7f7;
  padding-bottom: 20px;
}

header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px;
  background-color: #ff6b01;
  color: white;
  position: sticky;
  top: 0;
  z-index: 10;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  
  .fa-arrow-left {
    font-size: 18px;
    cursor: pointer;
    width: 24px;
  }
  
  .title {
    font-size: 18px;
    font-weight: bold;
  }
  
  .placeholder {
    width: 24px;
  }
}

.content {
  padding: 15px;
}

.status-card {
  background-color: #ff6b01;
  color: white;
  border-radius: 12px;
  padding: 15px;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  
  .status-icon {
    font-size: 28px;
    margin-right: 12px;
  }
  
  .status-info {
    .status-text {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 3px;
    }
    
    .status-desc {
      font-size: 13px;
      opacity: 0.9;
    }
  }
}

.info-card {
  background-color: white;
  border-radius: 12px;
  margin-bottom: 15px;
  overflow: hidden;
  
  .card-title {
    padding: 15px;
    border-bottom: 1px solid #f5f5f5;
    display: flex;
    align-items: center;
    
    i {
      color: #ff6b01;
      margin-right: 10px;
      font-size: 16px;
    }
    
    span {
      font-size: 16px;
      font-weight: 500;
      color: #333;
    }
  }
}

.business-info {
  padding: 15px;
  display: flex;
  align-items: center;
  
  .business-logo {
    width: 50px;
    height: 50px;
    margin-right: 15px;
    
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      border-radius: 8px;
    }
  }
  
  .business-detail {
    .business-name {
      font-size: 16px;
      font-weight: 500;
      color: #333;
      margin-bottom: 8px;
    }
    
    .business-contact {
      font-size: 14px;
      color: #666;
      display: flex;
      align-items: center;
      
      i {
        margin-right: 5px;
        color: #ff6b01;
      }
    }
  }
}

.delivery-info {
  padding: 15px 0;

  .address-info {
    padding: 15px;
    .contact-row {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 12px;

      .contact {
        display: flex;
        align-items: center;
        
        .name {
          font-size: 16px;
          font-weight: 500;
          margin-right: 15px;
          color: #333;
        }

        .phone {
          color: #666;
          font-size: 14px;
        }
      }

      .tag {
        font-size: 12px;
        color: #ff6b01;
        background-color: #fff8f3;
        padding: 2px 8px;
        border-radius: 4px;
        border: 1px solid #ffd8c0;
      }
    }

    .address {
      display: flex;
      align-items: flex-start;
      color: #666;
      font-size: 14px;
      line-height: 1.5;

      i {
        color: #ff6b01;
        margin-right: 8px;
        margin-top: 3px;
        font-size: 16px;
      }

      span {
        flex: 1;
      }
    }
  }
}

.no-address {
  padding: 20px 0;
  text-align: center;
  color: #999;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;

  i {
    margin-right: 6px;
    color: #ff6b01;
  }
}

.order-info-list {
  padding: 0 15px;
  
  .info-item {
    display: flex;
    justify-content: space-between;
    padding: 12px 0;
    border-bottom: 1px solid #f5f5f5;
    
    &:last-child {
      border-bottom: none;
    }
    
    .item-label {
      font-size: 14px;
      color: #666;
    }
    
    .item-value {
      font-size: 14px;
      color: #333;
      font-weight: 500;
    }
  }
}

.food-list {
  .empty-data {
    padding: 30px 15px;
    text-align: center;
    color: #999;
    font-size: 14px;
  }
  
  .food-item {
    padding: 15px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #f5f5f5;
    
    &:last-child {
      border-bottom: none;
    }
    
    .food-info {
      display: flex;
      align-items: center;
      flex: 1;
      
      .food-detail {
        flex: 1;
        
        .food-name-row {
          display: flex;
          justify-content: space-between;
          align-items: center;
          
          
          .food-name {
            font-size: 14px;
            color: #333;
            
          }
          
          .food-quantity {
            font-size: 13px;
            margin-right: 100px;
          }
        }
      }
    }
    
    .food-price {
      font-size: 14px;
      color: #333;
      font-weight: 500;
    }
  }
}

.price-detail {
  padding: 0 15px;
  
  .price-item {
    display: flex;
    justify-content: space-between;
    padding: 12px 0;
    border-bottom: 1px solid #f5f5f5;
    
    .item-label {
      font-size: 14px;
      color: #666;
    }
    
    .item-value {
      font-size: 14px;
      color: #333;
    }
    
    &.total {
      border-bottom: none;
      padding-top: 15px;
      
      .item-label {
        font-size: 16px;
        font-weight: 500;
        color: #333;
      }
      
      .item-value {
        font-size: 16px;
        color: #ff6b01;
        font-weight: bold;
      }
    }
  }
}

/* 修改底部按钮样式 */
.action-bar {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  margin-top: 15px;
  
  .btn-cancel, .btn-pay, .btn-again {
    padding: 10px 20px;
    border-radius: 20px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    border: none;
    transition: all 0.2s ease;
    
    &:active {
      transform: scale(0.97);
    }
  }
  
  .btn-pay, .btn-again {
    background-color: #ff6b01;
    color: white;
    box-shadow: 0 2px 6px rgba(255, 107, 1, 0.2);
  }
  
  .btn-cancel {
    background-color: #f5f5f5;
    color: #606266;
    border: 1px solid #dcdfe6;
  }
}

.loading {
  height: 80vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  
  .loading-spinner {
    font-size: 40px;
    color: #ff6b01;
    margin-bottom: 15px;
  }
  
  .loading-text {
    font-size: 16px;
    color: #666;
  }
}
</style> 